package com.yugao.fintech.antelope.base.feign.interceptor;

import com.yugao.fintech.antelope.base.model.constants.RequestCons;
import com.yugao.fintech.antelope.base.model.constants.SecurityCons;
import com.yugao.fintech.antelope.base.model.module.auth.LoginUserHolder;
import com.yugao.fintech.antelope.base.model.module.tenant.TenantContextHolder;
import com.yugao.fintech.framework.core.utils.ServletUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * feign 请求拦截器 oauth2 feign token传递
 */
@RequiredArgsConstructor
@ConditionalOnClass({FeignAutoConfiguration.class})
public class FeignTokenRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        Collection<String> authorization = template.headers().get(HttpHeaders.AUTHORIZATION);
        Collection<String> fromHeader = template.headers().get(SecurityCons.FROM_SOURCE);
        template.header(RequestCons.Headers.TENANT_ID, String.valueOf(TenantContextHolder.get().getTenantId()));

        // 非web 请求直接跳过
        if (!ServletUtils.getRequest().isPresent()) {
            return;
        }

        HttpServletRequest request = ServletUtils.getRequestOfNonNull();
        template.header(RequestCons.Headers.SYSTEM_TYPE, request.getHeader(RequestCons.Headers.SYSTEM_TYPE));
        template.header(RequestCons.Headers.LOGIN_USER, LoginUserHolder.get().encodeToString());
    }
}